var usersApp = angular.module("usersApp", ["ui.bootstrap","ngRoute"]);
//contextPath: Se obtiene desde el controlador y sirve para determinar la url actual

usersApp
    .run(function($rootScope){
        $rootScope.userTypes = [
        {id:1, tipo:"Administrador", labelRoute:"Admin", gridCaption:"Administradores"},
        {id:2, tipo:"Conductor", labelRoute:"Driver", gridCaption:"Conductores"},
        {id:3, tipo:"Cliente", labelRoute:"Client", gridCaption:"Clientes"},
        {id:4, tipo:"Secretaria", labelRoute:"Secretary", gridCaption:"Secretarias"},
        {id:6, tipo:"Almacenista",labelRoute:"Storer", gridCaption:"Almacenistas"},
        {id:7, tipo:"Controlador de Operaciones", labelRoute:"OperationController", gridCaption:"Controladores de Operación"},
        {id:8, tipo:"Director Ejecutivo", labelRoute:"CEO", gridCaption:"Directores Ejecutivos"},
        ];
        
        $rootScope.userType = null;
    })
    .factory('users', dataFactory)
    .factory('utils',utilsFactory)
    .factory('gridConfig',gridConfigFactory)
    .service('modalService',modalService)
    .directive('ngJqgrid', ngJqgrid)
    .config(function ($routeProvider, $locationProvider) {
        $locationProvider.hashPrefix('!');
        $routeProvider
            .when('/index',
                {
                    controller: 'indexController',
                    templateUrl: 'index.html'
                })        
            .when('/edit/:id',
                {
                    controller: 'editController',
                    templateUrl: 'edit.html'
                })
            .when('/:label',
                {
                   controller: 'indexController',
                   templateUrl: 'index.html'
                })
            .when('/:label/edit/:id',
                {
                   controller: 'editController',
                   templateUrl: 'edit.html'
                })
            .otherwise({ redirectTo: '/index' });
    });


usersApp.controller("indexController", function($rootScope,$scope, $location, $routeParams, users, utils, modalService, gridConfig) {
    $scope.currentPath = $location.path();
    $scope.basePath = $routeParams.label;
    $scope.gridCaption = "Usuarios";
    
    if($routeParams.label){
        $scope.userType = utils.getPropFromArray($scope.userTypes, "labelRoute", $routeParams.label, "id")
        $rootScope.userType =  $scope.userType;
        $scope.gridCaption = utils.getPropFromArray($scope.userTypes, "labelRoute", $routeParams.label, "gridCaption");         
    }
        
    $scope.init = function(){
        $(window).on('resize', function(event, ui) {
            var parWidth = $("#gbox_grdUsers01").parent().parent().parent().width();
            var curWidth = $("#gbox_grdUsers01").width();
            var w = parWidth - 1;
            if (Math.abs(w - curWidth) > 2)
            {  
                $("#grdUsers01").setGridWidth(w);
            }
        }).trigger('resize');
    }
    
    $scope.getCurrentRouteClass = function (path) {
        if ($location.path().substr(0, path.length) == path) {
            return true
        } else {
            return false;
        }
    }
    
    $scope.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.goEdit = function(path){
        if($scope.userId)
           $scope.go(path); 
        else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder editar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    $scope.alerts = [];
    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };
  
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {
                closeButtonText: 'Cancelar',
                actionButtonText: 'Eliminar',
                bodyText: '¿Estás seguro de eliminar este usuario?'
            };
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.loading = true;
                users.delete(contextPath + "delete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.loading = false;
                    if(data.error){
                        var modalOptions = {
                        actionButtonText: 'Aceptar',
                        bodyText: data.error
                    };
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                       var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro eliminado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                            $scope.grid.api.refresh();
                        });
                    }                    
                    })
                .error(function(data, status, headers, config) {
                    $scope.loading = false;
                    var modalOptions = {
                        actionButtonText: 'Aceptar',
                        bodyText: 'Ocurrió un error al eliminar el registro.'
                    };
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
            });
        }else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    $scope.grid = {}
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getUsers",	
	colNames: ["id", "Clave", /*"Nombre Comercial", "Categoría", */"Nombre", "Apellidos", "Usuario", "Tipo de Usuario"],
	colModel: [
		{name: "id", width: 40, align: "right", hidden: true},
                {name: "code", index: "code", width: 60},
                /*{name: "commercial_name", index: "commercial_name", width: 120},
                {name: "category", index: "category", width: 80},*/
		{name: "first_name", index: "first_name", width: 80},
                {name: "last_name", index: "last_name", width: 100},
		{name: "username", index: "username", width: 50},
                {name: "tipo", index: "tipo", width: 50}                
	],
	sortname: "first_name",
	sortorder: "asc",
	caption: $scope.gridCaption,
        beforeRequest: function(){
            $scope.loading = true;
        },
        onSelectRow: function(id){
            $scope.$apply(function(){
                $scope.selRow = id;
                $scope.userId = $scope.grid.apicall('getRowData', id).id
            });
            
        },
        loadComplete: function (data) {
            $scope.loading = false;
            $scope.$apply(function(){
                $rootScope.data = data; 
                $scope.selRow =null;
                $scope.userId = null;
            });
           $scope.init();
        },
        serializeGridData: function(postData) {
            postData.type = $scope.userType;
            return JSON.stringify(postData);
        }
    },{id: "id"});
});

usersApp.controller("editController", function($rootScope,$scope, $location, $routeParams, users, utils, modalService) {
    $scope.currentPath = $location.path();
    $scope.basePath = $routeParams.label;
    console.log($scope.userType);
    $scope.ev = function(){
         console.log($scope.user.code, $scope.frmUser.code);
    }
    init();
    console.log("form valid: ", $scope.frmUser.$invalid)
    function init() {
        //Catálogos Iniciales
        
        
        $scope.userStatus= [
        {id:0,status:"Inactivo"},
        {id:1,status:"Activo"},
        {id:2,status:"Bloqueado"}
        ];
        
        //Asignaciones Iniciales
        $scope.user = {};
        setSelectedUserStatus(1);
        if($scope.userType)
            setSelectedUserType($scope.userType);
        
        $scope.frmUser ={};
        
        var userId = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (userId > 0) {
            if($scope.data){
                $scope.user = utils.findById($scope.data[0],'id',userId);                
                setSelectedUserType($scope.user.type);
                setSelectedUserStatus($scope.user.status);
            }else{
                users.getData(contextPath + "getUsers", {page: 1, rowsPerPage: 1, sortField: 'name', sortDir: 'asc', id: userId})
                    .success(function(data, status, headers, config) {
                       $scope.user = data[0][0];
                        setSelectedUserType($scope.user.type);
                        setSelectedUserStatus($scope.user.status);
                    })
                    .error(function(data, status, headers, config) {
                        alert('Error');
                    });
            }
        }
    }
    
    $scope.save = function(){
        if($scope.user){
            $scope.loading=true;
            users.save(contextPath + "save", $scope.user, {})
                .success(function(data, status, headers, config){
                    $scope.loading=false;
                    if (data.error) {
                         var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions)
                    } else {
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro guardado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                                $location.path('/'+$scope.basePath);
                            });
                        }
                })
                .error(function(data, status, headers, config){
                    $scope.loading = false;
                    alert('Error');
                });
        }
    }
    
    function setSelectedUserType(value){
        for(var i=0;i<$scope.userTypes.length;i++){
            if($scope.userTypes[i]["id"]==value){
                $scope.user.type = $scope.userTypes[i]["id"];
                return;
            }
        }
    }
    
    function setSelectedUserStatus(value){
        for(var i=0;i<$scope.userStatus.length;i++){
            if($scope.userStatus[i]["id"]==value){
                $scope.user.status = $scope.userStatus[i]["id"];
                return;
            }
        }
    }
    
    $scope.getFormFieldCssClass = function(ngModelController) {
        if(ngModelController.$pristine) return "";
        return ngModelController.$valid ? "has-success" : "has-error";
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
});

usersApp.controller("storerIndexController",function($rootScope,$scope, $location, users, modalService, gridConfig){
    $scope.userType = 6;
    $scope.init = function(){
        $(window).on('resize', function(event, ui) {
            var parWidth = $("#gbox_grdUsers01").parent().parent().parent().width();
            var curWidth = $("#gbox_grdUsers01").width();
            var w = parWidth - 1;
            if (Math.abs(w - curWidth) > 2)
            {  
                $("#grdUsers01").setGridWidth(w);
            }
        }).trigger('resize');
    }
    
    $scope.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.goEdit = function(path){
        if($scope.userId)
           $scope.go(path); 
        else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder editar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    $scope.alerts = [];
    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };
  
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {
                closeButtonText: 'Cancelar',
                actionButtonText: 'Eliminar',
                bodyText: '¿Estás seguro de eliminar este usuario?'
            };
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.loading = true;
                users.delete(contextPath + "delete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.loading = false;
                    if(data.error){
                        $scope.alerts.push({type: "danger",msg: 'Error al eliminar el registro'});                     
                    }else{
                        $scope.alerts.push({type: "success",msg: '¡Registro Eliminado!'});    
                    }
                    $scope.grid.api.refresh();
                    })
                .error(function(data, status, headers, config) {
                    $scope.loading = false;
                    alert('Error');
                });
            });
        }else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    $scope.grid = {}
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getUsers",	
	colNames: ["id", "Clave", "Nombre Comercial", "Categoría", "Nombre", "Apellidos", "Usuario", "Tipo de Usuario"],
	colModel: [
		{name: "id", width: 40, align: "right", hidden: true},
                {name: "code", index: "code", width: 60},
                {name: "commercial_name", index: "commercial_name", width: 120},
                {name: "category", index: "category", width: 80},
		{name: "first_name", index: "first_name", width: 80},
                {name: "last_name", index: "last_name", width: 100},
		{name: "username", index: "username", width: 50},
                {name: "tipo", index: "tipo", width: 50}                
	],
	sortname: "commercial_name",
	sortorder: "asc",
	caption: "Usuarios",
        onSelectRow: function(id){
            $scope.$apply(function(){
                $scope.selRow = id;
                $scope.userId = $scope.grid.apicall('getRowData', id).id
            });
            
        },
        loadComplete: function (data) {        
            $scope.$apply(function(){
                $rootScope.data = data; 
                $scope.selRow =null;
                $scope.userId = null;
            });
           $scope.init();
        },
        serializeGridData: function(postData) {
            postData.type = $scope.userType;
            return JSON.stringify(postData);
        }
    },{id: "id"});
});